<template>
    <view class="container" v-if="assistanceDetail">
        <view class="assistance_banner">
            <image mode="widthFix" :src="assistanceDetail.topImage" class="assistance_banner_img"></image>
        </view>
       <view class="mian_assistance_block" :style="{background: assistanceDetail.backgroundColor||'#fff'}">
           <view class="assistance_detail_block">
               <image class="assistance_detail_bg" src="https://image1.sansancloud.com/xianhua/2020_5/25/15/1/9_479.jpg?x-oss-process=style/preview"></image>
               <view class="assistance_detail_info">
                   <text class="count_down_text" :style="{color:assistanceDetail.frontColor||defaultColor}">“ 距离结束 ”</text>
                   <view class="count_down_time">
                       <time-component ref='assistancesDetailTime' v-if="assistanceDetail&&!clearTimeState" showType='zhuli' :bgColor="assistanceDetail.frontColor" :receiveData="assistanceDetail.endDatetime"></time-component>
                   </view>
                   <view class="assistance_detail_remain_block">
                       <text>活动剩余数量：</text>
                       <view class="assistance_detail_remain_num">
                           <text class="assistance_detail_remain_num_item" v-for="(numItem,numIndex) in assistanceDetail.leftStock+''" :key="numIndex" :style="{background:assistanceDetail.frontColor||defaultColor}">{{numItem}}</text>
                       </view>
                       <text>个</text>
                   </view>
                   <!-- <view class="assistance_friend_list_block">
                       <scroll-view scroll-x class="assistance_friend_list" scroll-with-animation='true' :scroll-into-view="'friend_'+curFriendIndex">
                           <view class='assistance_friend_item' v-for="(item,index) in 3" :key="index" :id="'friend_'+index">
                             <view class='assistance_friend_icon'>
                                <image class='assistance_friend_icon_img' src=''></image>
                             </view>
                             <text class='assistance_friend_name'>赵同学</text>
                           </view>
                           <view class='assistance_friend_item' v-for="(item,index) in 7" :key="index" :id="'friend_'+(index+3)">
                             <view class='assistance_friend_icon'>
                                 <text>?</text>
                             </view>
                             <text class='assistance_friend_name'>待邀请</text>
                           </view>
                       </scroll-view>
                   </view>
                   <view class="assistance_friend_progress_block">
                       <view class="assistance_friend_progress">
                           <view class="assistance_friend_progress_line" :style="{background:assistanceDetail.frontColor,width:'30%'}"></view>
                       </view>
                       <text class="assistance_friend_progress_ratio">
                           助力进度：3/10
                       </text>
                   </view> -->
                   <text class="assistance_state_block">
                       本轮助力已开始
                   </text>
                   <view class="assistance_btn_block" v-if="!assistanceDetail.platformUserRecord" :style="{background: assistanceDetail.buttonColor||defaultColor}" @tap="attendAssistanceFun()">
                       <text class="assistance_btn_text" v-if="assistanceDetail.platformUserCanCreateAssistance==1">立即发起助力</text>
                       <text class="assistance_btn_text" v-else>{{assistanceDetail.platformUserCanNotCreateAssistanceReson}}</text>
                   </view>
                   <view class="assistance_btn_block" v-else :data-url="'transpond_assistances.html?recordId='+assistanceDetail.platformUserRecord.id+'&assistanceId='+assistanceDetail.id" @tap="tolinkUrl" :style="{background: assistanceDetail.buttonColor||defaultColor}">
                       <text class="assistance_btn_text">进入助力页面</text>
                   </view>
                   <text class="user_view_block">
                       已有{{assistanceDetail.viewCount}}人浏览
                   </text>
               </view>
           </view>
           <view class="assistance_item_block">
               <text class="count_down_text" :style="{color:assistanceDetail.frontColor||defaultColor}">“ 活动规则 ”</text>
               <view class="assistance_rules_list">
                   <view class="assistance_rules_item">
                       <image src="https://image1.sansancloud.com/xianhua/2020_5/22/14/6/46_893.jpg?x-oss-process=style/preview_120" class="assistance_rules_item_img"></image>
                       <text class="assistance_rules_item_text">开启助力</text>
                   </view>
                   <image class="assistance_rules_item_arrow" src="https://image1.sansancloud.com/xianhua/2020_5/22/14/6/46_866.jpg?x-oss-process=style/preview_120"></image>
                   <view class="assistance_rules_item">
                       <image src="https://image1.sansancloud.com/xianhua/2020_5/22/14/6/46_890.jpg?x-oss-process=style/preview_120" class="assistance_rules_item_img"></image>
                       <text class="assistance_rules_item_text">邀请好友</text>
                   </view>
                   <image class="assistance_rules_item_arrow" src="https://image1.sansancloud.com/xianhua/2020_5/22/14/6/46_866.jpg?x-oss-process=style/preview_120"></image>
                   <view class="assistance_rules_item">
                       <image src="https://image1.sansancloud.com/xianhua/2020_5/22/14/6/46_885.jpg?x-oss-process=style/preview_120" class="assistance_rules_item_img"></image>
                       <text class="assistance_rules_item_text">助力成功</text>
                   </view>
                   <image class="assistance_rules_item_arrow" src="https://image1.sansancloud.com/xianhua/2020_5/22/14/6/46_866.jpg?x-oss-process=style/preview_120"></image>
                   <view class="assistance_rules_item">
                       <image src="https://image1.sansancloud.com/xianhua/2020_5/22/14/6/46_887.jpg?x-oss-process=style/preview_120" class="assistance_rules_item_img"></image>
                       <text class="assistance_rules_item_text">领取奖励</text>
                   </view>
               </view>
               <view class="description_block" v-if="assistanceDetail.description">
                   <!-- <text class="description_title">【活动简介】</text> -->
                   <view class="description_text">
                       <text>【活动简介】</text>
                       <!-- 「  」 -->
                       <text>{{assistanceDetail.description}}</text>
                   </view>
               </view>
           </view>
           <view class="assistance_item_block">
               <text class="count_down_text" :style="{color:assistanceDetail.frontColor||defaultColor}">“ 奖励榜单 ”</text>
               <view class="assistance_reward_list_block">
                   <view class="assistance_reward_list_title">
                       <view class="assistance_reward_list_title_item" style="width: 10%;"><text>排名</text></view>
                       <view class="assistance_reward_list_title_item"><text>头像</text></view>
                       <view class="assistance_reward_list_title_item" style="width: 25%;"><text>昵称</text></view>
                       <view class="assistance_reward_list_title_item" style="width: 15%;"><text>助力数</text></view>
                       <view class="assistance_reward_list_title_item" style="width: 30%;"><text>奖励</text></view>
                   </view>
                   <view class="assistance_reward_list" v-if="assistanceSuccessRecordList.length!=0">
                       <view class="assistance_reward_item" v-for="(item,index) in assistanceSuccessRecordList" :key="index">
                           <view class="assistance_reward_list_item" style="width: 10%;">{{index+1}}</view>
                           <view class="assistance_reward_list_item">
                               <image :src="item.platformUserIcon" class="item_img"></image>
                           </view>
                           <view class="assistance_reward_list_item" style="width: 25%;">{{item.platformUserName}}</view>
                           <view class="assistance_reward_list_item" style="width: 15%;">{{item.needAssistCount}}</view>
                           <view class="assistance_reward_list_item" style="width: 30%;">{{item.rewardRemark}}</view>
                       </view>
                   </view>
                   <view v-else class="no_assistance_reward_list">暂无数据~</view>
               </view>
               <view class="assistance_reward_more" v-if="assistanceSuccessRecordList.length!=0" @click="loadMoreSuccessRecordFun">
                   查看更多
               </view>
           </view>
       </view>
       <!-- 填写表单弹窗动画 -->
       <view class='zhezhao' v-if="showAttendForm" @tap='closeZhezhao'></view>
       <view class='popupFormDetail' :animation="animationData">
         <view class='form_title' >
           <text ></text>
           <text>请填写以下信息</text>
           <image class='close_popup_icon' src='https://image1.sansancloud.com/xianhua/2019_7/31/15/25/40_755.jpg?x-oss-process=style/preview_120' @click='closeZhezhao'></image>
         </view>
         <scroll-view scroll-y  style='max-height:700rpx'>
           <view v-if="sendOptionData&&showAttendForm">
              <form-detail-component id="submitAssistanceForm" :receiveData="sendOptionData" :showTitle="true" :showBtn="false" @sendDataFun="getDataFun"></form-detail-component><!-- 弹窗-->
           </view>
           </scroll-view>
       </view>
       <view v-if="sendOptionData&&showAttendForm" class='submitBtn' :style='{background:assistanceDetail.buttonColor||defaultColor}' @click='submitData'>
         <text>创建助力活动</text>
       </view>
    </view>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
export default {
  data() {
    return {
      assistanceDetail:null,
      assistanceId:0,
      setting:null,
      loginUser:null,
      secondColor:'',
      defaultColor:'',
      showAttendForm:false,
      animationData:null,
      sendOptionData:null,
      clearTimeState:false,
      listPage:{
          page: 1,
          pageSize: 20,
          totalSize: 0,
          assistanceId: "",
      },
      options:null,
      curFriendIndex:2,
      assistanceSuccessRecordList:[],
    };
  },
  props: {},

  /*onload*/
  onLoad: function (options) {
    let that=this;
    let loginUser=getApp().globalData.loginUser||null;
    that.setData({options:options})
    if (loginUser) {
      that.checkState(options);
    } else {
      getApp().globalData.addLoginListener(that);
      let url='login.html?url=';
      let backUrl='assistances_detail.html?assistanceId='+options.assistanceId;
      url+= encodeURIComponent(backUrl)
      getApp().globalData.linkEvent(url)
    }
    console.warn("======onLoad:options======", options, getApp().globalData.setting);
  },
  onReady: function () {
    
  },
  onShow: function () {
    let that=this;
    if(that.clearTimeState){
        that.setData({clearTimeState:false})
    }
	that.setData({
        setting:getApp().globalData.setting,
        defaultColor:getApp().globalData.setting.platformSetting.defaultColor,
        secondColor:getApp().globalData.setting.platformSetting.secondColor,
       })
    wx.setNavigationBarColor({
      frontColor: getApp().globalData.setting.platformSetting?getApp().globalData.setting.platformSetting.topColor.toLowerCase():'',
      backgroundColor: getApp().globalData.setting.platformSetting?getApp().globalData.setting.platformSetting.topBgColor:''
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      let that=this;
      console.log("==this.$refs===",that.$refs)
      that.setData({clearTimeState:true})
      try{
          that.$refs.assistancesDetailTime.setShowTimeStateFun(true);
      }catch(e){
          //TODO handle the exception
      }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      let that=this;
      console.log("==this.$refs===",that.$refs)
      that.setData({clearTimeState:true})
      try{
          that.$refs.assistancesDetailTime.setShowTimeStateFun(true);
      }catch(e){
          //TODO handle the exception
      }
  },
  /* 分享 app.js862行*/
  onShareAppMessage: function () {
    console.log(getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  onPullDownRefresh: function () {
    let that = this; // 下拉刷新的时候首先判断存不存在tab
    console.log("下拉");
    if (getApp().globalData.loginUser) {
      that.checkState(that.options);
    } else {
      getApp().globalData.addLoginListener(that);
    }
    that.getData(that.assistanceId);
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this
    // if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
    //   that.listPage.page++
    //   that.findAssistanceSuccessRecordFun(that.listPage,'upload');
    // }else{
    //     wx.showToast({
    //       title: "到底了~",
    //       image: '/wxcomponents/images/icons/tip.png',
    //       duration: 1000
    //     });
    // }
  },
  methods: {
    loadMoreSuccessRecordFun:function(){
        console.log('===onReachBottom====');
        let that = this
        if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
          that.listPage.page++
          that.findAssistanceSuccessRecordFun(that.listPage,'upload');
        }else{
            wx.showToast({
              title: "没有更多了~",
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
        }
    },
    checkState: function (options) {
      let that = this;
      console.log('======checkState.loginUser======', getApp().globalData.loginUser,getApp().globalData.setting);
      if(options.assistanceId){
          that.setData({assistanceId:options.assistanceId})
          that.getData(options.assistanceId);
          that.listPage.assistanceId=options.assistanceId
      }
      that.setData({
        loginUser: getApp().globalData.loginUser
      });
    },
    findAssistanceSuccessRecordFun:function(param){
        let that = this
        let params={}
        console.log("===params==",params,param)
        params=Object.assign({},params,param)
        var customIndex = getApp().globalData.AddClientUrl("/wx_find_assistance_success_records.html", params)
        getApp().globalData.showToastLoading('loading', true)
        wx.request({
          url: customIndex.url,
          header: getApp().globalData.header,
          success: function (res) {
            wx.hideLoading()
            console.log(res.data)
            let data=res.data.relateObj.result;
            that.listPage.pageSize = res.data.relateObj.pageSize
            that.listPage.page = res.data.relateObj.curPage
            that.listPage.totalSize = res.data.relateObj.totalSize
            let dataArr = that.assistanceSuccessRecordList;
            console.log("===data====",data)
            if (param.page == 1) {
              dataArr = []
            }
            if (!data || data.length == 0) {
              that.setData({ assistanceSuccessRecordList: [] })
            } else {
              if (dataArr == null) { dataArr = [] }
              dataArr = dataArr.concat(data)
              that.setData({ assistanceSuccessRecordList: dataArr })
            }
            wx.hideLoading()
          },
          fail: function (res) {
            console.log("fail")
            wx.hideLoading()
            getApp().globalData.loadFail()
          }
        })
    },
    attendAssistanceFun:function(){
        let that=this;
        if(that.assistanceDetail.platformUserCanCreateAssistance==0){
            wx.showToast({
              title: that.assistanceDetail.platformUserCanNotCreateAssistanceReson,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
            return
        }
        if(!that.assistanceDetail.assistRecordFormId){
            that.submitAttendAssistanceFun()
        }else{
            let showAttendForm=!that.showAttendForm;
            that.setData({
              sendOptionData: { customFormId: that.assistanceDetail.assistRecordFormId },
              showAttendForm: showAttendForm,
            })
            let animation = wx.createAnimation({
              duration: 400,
              timingFunction: 'ease',
            })
            console.log("showAttendForm",showAttendForm,that.sendOptionData)
            if (showAttendForm) {
              animation.bottom('100rpx').step()
            } else {
              animation.bottom('-200rpx').step()
            }
            that.setData({
              animationData: animation.export(),
            })
        }
    },
    submitData:function(){
        let that=this;
        that.selectComponent("#submitAssistanceForm").formSubmit();
    },
    getDataFun: function (e) {
      let that = this;
      console.log("===getDataFun===", e, e.detail.formId)
      that.submitAttendAssistanceFun(e.detail.formId)
    },
    closeZhezhao:function(){
      console.log("======closeZhezhao=========")
      let that=this;
      that.setData({ showAttendForm: false })
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease',
      })
      animation.bottom('-200rpx').step()
      let setData = animation.export()
      that.setData({
        animationData: setData,
      })
    },
    submitAttendAssistanceFun:function(formCommitId){
      var that = this
      let params={
          assistanceId:that.assistanceDetail.id,
          formRecordCommitId:formCommitId||0,
      }
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_create_or_get_assistance_record.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          that.closeZhezhao()
          let data=res.data.relateObj;
          if(res.data.errcode==0){
              wx.showToast({
                title: "参与成功",
                icon:'success',
                duration: 1000
              });
              setTimeout(function(){
                let url="transpond_assistances.html?recordId="+data.id+"&assistanceId="+that.assistanceId;
                that.findAssistanceSuccessRecordFun(that.listPage);
                that.tolinkUrl(url)
              },1000)
          }else{
              wx.showToast({
                title: res.data.errMsg,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 1000
              });
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    /* 获取数据 */
    getData: function (assistanceId) {
      var that = this
      let params={
          assistanceId:assistanceId
      }
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_assistance_detail.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj;
          that.listPage.assistanceId=data.id
          that.findAssistanceSuccessRecordFun(that.listPage)
          console.log("====data====",data)
          that.setData({ assistanceDetail: data })
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    lookBigImage: function (e) {
      console.log("111111111", e.currentTarget.dataset);
      let imgSrc = e.currentTarget.dataset.imageurl;
      let imgArray = [];
      let index = e.currentTarget.dataset.index;
      let PostImageSrc = [];
      console.log(imgSrc);

      for (let i = 0; i < imgSrc.length; i++) {
        imgArray.push(imgSrc[i]);
        PostImageSrc.push(imgSrc[i].replace(/http/, "https"));
      } 
      console.log(PostImageSrc);
      if (!imgSrc) {
        return;
      }
      wx.previewImage({
        current: imgArray[index],
        // 当前显示图片的http链接
        urls: imgArray // 需要预览的图片http链接列表

      });
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
      console.warn("=======e=======", e);
      let linkUrl = e.currentTarget?e.currentTarget.dataset.url:e;
      getApp().globalData.linkEvent(linkUrl);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>